<?php
global $AppUI;

// check permissions
$m = $AppUI->checkFileName(dPgetParam( $_GET, 'm', getReadableModule() ));
$denyEdit = getDenyEdit( $m );
if ($denyEdit) {
	$AppUI->setMsg('Access denied', UI_MSG_ERROR);
	$AppUI->redirect();
}

require_once $AppUI->getSystemClass('date');

require_once( $AppUI->getModuleClass( 'projects' ) );

$df = $AppUI->getPref('SHDATEFORMAT');

$tid = isset($_GET['tid']) ? $_GET['tid'] : 0;
$q = new DBQuery();
$task = array();
if ($tid > 0) {
	$q->addTable('task_log', 'tl');
	$q->addQuery('tl.*,t.task_project');
	$q->addJoin('tasks', 't', 'tl.task_log_task = t.task_id');
	$q->addWhere('task_log_id = '.$tid);
	$task = $q->loadHash();
	$task_project = $task['task_project'];
	$creator = isset($task['task_log_creator']) ? $task['task_log_creator'] : 0;
}
else {
	$creator = $AppUI->user_id;
}
$AppUI->savePlace();

if (isset( $task['task_log_date'] )) {
	$date = new CDate( $task['task_log_date'] );
} else if (isset( $_GET['date'] )) {
	$date = new CDate($_GET['date']);
} else {
	$date = new CDate();
}

$q->addTable('projects', 'p');
$q->addTable('project_contacts', 'pc');
$q->addQuery('p.project_id,p.project_name,p.project_owner');
$q->addWhere('p.project_id = pc.project_id');
$q->addWhere('p.project_status > 0 AND  p.project_status < 6');
$q->addWhere('pc.contact_id = '.$AppUI->user_id);
$projects = $q->loadHashList('project_id');

$project = array('0' => '-');
$taskList = '';
foreach ($projects as $id => $p) {
	$q->addTable('tasks', 't');
	$q->addQuery('t.task_id,t.task_name,t.task_percent_complete,t.task_project');
	if ($p['project_owner'] != $AppUI->user_id) {
		$q->addJoin('user_tasks', 'ut', 't.task_id = ut.task_id');
		$q->addWhere('ut.user_id = '.$AppUI->user_id);
	}
	$q->addWhere('t.task_project = '.$id);
	$q->addWhere('t.task_percent_complete < 100'.($id == $task_project ? ' OR t.task_id = '.$task['task_log_task'] : ''));
	$tasks = $q->loadHashList('task_id');
	if (count($tasks) > 0) {
		$project[$id] = $p['project_name'];

		$taskList .= '['.$id.',';
		foreach ($tasks as $zid => $t) {
			$taskList .= '['.$zid.',"'.addslashes(html_entity_decode($t['task_name'])).'",'.$t['task_percent_complete'].'],';
		}
		$taskList .= '0],'."\n";
	}
}

// TODO:
// Each project/company may have its own billing code
// => load Billing code for each project
$q = new DBQuery();
$q->addTable('billingcode');
$q->addQuery('billingcode_id,billingcode_name');
$q->addWhere('billingcode_status = 0');

$task_log_costcodes = $q->loadHashList();
$task_log_costcodes = array_merge(array(0 => 'None'), $task_log_costcodes);
?>

<script language="javascript">
var taskList = [
<?=$taskList?>
0];

function changeProject(sel) {
	var pid = sel.options[sel.selectedIndex].value;
	var t = $('idTaskList');

	t.options.length = 0;
	$('idTask_complete').value = 0;
	for (i in taskList) {
		if (taskList[i] == 0) return;
		var p = taskList[i];
		if (p[0] == pid) {
			var n = 0;
			t.options[n++] = new Option('-', 0);
			for (z = 1; p[z] != 0; z++) {
				var opt = new Option(p[z][1], p[z][0]);
				t.options[n++] = opt;
				opt.setAttribute('percent', p[z][2]);
			}
			break;
		}
	}
}

function changeTask(sel, tid) {
	if (typeof(tid) != 'undefined') {
		for (var i = 0; i < sel.options.length; i++)
			if (sel.options[i].value == tid) {
				sel.selectedIndex = i;
				break;
			}
	}

	var tc = $('idTask_complete');
	if (sel.selectedIndex <= 0)
		tc.value = 0;
	else {
		var p = sel.options[sel.selectedIndex].getAttribute('percent');
		if (p && p != '') tc.value = p;
		$('idTaskName').value = sel.options[sel.selectedIndex].text;
	}
}

function doSave() {
	var f = document.AddEdit;

	if (f.task_log_description.value.length < 1) {
		alert( "Please enter a worthwhile comment." );
		f.task_log_description.focus();
	} else if (f.task_project.selectedIndex == 0) {
		alert( "You must select a Project." );
		f.task_project.focus();
	} else if (f.task_log_task.selectedIndex == 0) {
		alert( "You must select a Task." );
		f.task_log_task.focus();
	} else {
		f.submit();
	}
}

function doCancel()
{
	if (confirm('Are you sure you want to cancel.')) {
		location.href = './index.php?m=timecard&tab=0';
	}
}

function doDelete() {
	if (confirm( "Are you sure that you would like to delete this task log?\n" )) {
		var form = document.AddEdit;
		form.del.value=1;
		form.submit();
	}
}

function createNewTask() {
	var p = $('idProjectList');
	if (p.selectedIndex <= 0) {
		alert('Please select a project');
		return;
	}
	go('?m=tasks&a=simpleaddedit&task_project='+p.options[p.selectedIndex].value);
}
</script>

<form name="AddEdit" action="" method="post">
<input type="hidden" name="m" value="timecard">
<input type="hidden" name="tab" value="0">
<input type="hidden" name="dosql" value="do_updatetasklog">
<input type="hidden" name="del" value="0">
<input type="hidden" name="task_log_id" value="<?=$tid?>">
<input type="hidden" name="task_log_creator" value="<?=$creator?>"/>

<table cellspacing="0" cellpadding="4" border="0" width="100%" class="infopanel">
<tr>
	<td>
		<input class="button" type="button" name="btnFuseAction" value="save" onClick="doSave();">
	</td>
	<td>
		<input class="button" type="button" name="Cancel" value="cancel" onClick="doCancel()">
	</td>
	<td width="100%" align="right">
	<?	if ($tid > 0) { ?>
		<a class="button" href="javascript:doDelete()"><img align="absmiddle" src="images/delete_log.gif" title="Delete">&nbsp;<?=$AppUI->_('delete task log')?></a>
	<?	} ?>&nbsp;
	</td>
</tr>
</table>
<table cellspacing="0" cellpadding="4" border="0" width="100%" class="subinfopanel">
<tr>
	<td align="right" nowrap="nowrap"><b><?=$AppUI->_('Project')?>:</b></td>
	<td colspan="5">
		<?
			$params = 'id="idProjectList" size="1" class="text" style="width:350px" ';
			$params .= 'onchange="changeProject(this)"';
			echo arraySelect( $project, 'task_project', $params, $task_project);
		?>
	</td>
</tr>
<tr>
	<td align="right" nowrap="nowrap"><b><?=$AppUI->_('Task')?>:</b></td>
	<td colspan="5">
		<select id="idTaskList" name="task_log_task" class="text" style="width:350px" onchange="changeTask(this)"></select>
		<input id="idTaskName" type="hidden" name="task_log_name" value="">
	</td>
	<td width="100%" style="padding-left: 0px">
		<input type="image" src="images/add_task.gif" onclick="createNewTask(); return false" class="button" title="Create new task"/>
	</td>
</tr>
<tr>
	<td align="right" nowrap="nowrap"><b><?=$AppUI->_('Date')?></b>:</td>
	<td nowrap="nowrap">
		<input id="idDateLog" type="hidden" name="task_log_date" value="<?=$date->format(FMT_TIMESTAMP_DATE)?>">
		<input id="idDateLogD" style="width: 70px" type="text" name="date" value="<?=$date->format($df)?>" class="text" disabled="disabled">
		<img id="idDateLogB" align="absmiddle" src="images/calendar.gif" title="<?=$AppUI->_('Calendar')?>">
	</td>
	<td align="right" nowrap="nowrap"><b><?=$AppUI->_('Hours')?></b>:</td>
	<td>
		<?=showSpinBox('task_log_hours', ($tid > 0) ? $task['task_log_hours'] : '0', 0, 9, '', 0.5)?>
	</td>
	<td align="right" nowrap="nowrap"><b><?=$AppUI->_('Completion')?></b>:</td>
	<td>
		<?=showSpinBox('task_complete', '0', 0, 100, '%', 5, false, 25)?>
	</td>
</tr>
<tr>
	<td align="right" valign="top" nowrap="nowrap"><b><?=$AppUI->_('Description')?></b>:</td>
	<td align="left" colspan="5">
		<textarea name="task_log_description" style="width: 350px" rows="6" wrap="virtual" class="textarea"><?php echo (($tid > 0) ? $task["task_log_description"] : "");?></textarea>
	</td>
</tr>
<tr style="display: none">
	<td align="right" nowrap="nowrap"><?=$AppUI->_('Cost Code')?>:</td>
	<td align="left" colspan="5">
		<?php
			echo arraySelect( $task_log_costcodes, 'task_log_costcodes', 'size="1" class="text" onchange="javascript:task_log_costcode.value = this.options[this.selectedIndex].value;"', '' );
		?>
		&nbsp;->&nbsp;<input type="text" class="text" name="task_log_costcode" value="<?php echo $task["task_log_costcode"]//$log->task_log_costcode;?>" maxlength="8" size="8" />
	</td>
</tr>
<tr>
	<td>&nbsp;</td>
	<td align="left" colspan="6" width="100%" valign="top" style="padding: 0px">
		<table border="0" cellspacing="0" cellpadding="0">
			<tr>
				<td><input id="idTaskProblem" type="checkbox" value="1" name="task_log_problem" <? echo $task["task_log_problem"] ? 'checked="checked"' : ''; ?> /></td>
				<td><label for="idTaskProblem"><?php echo $AppUI->_('Problem');?></label></td>
			</tr>
		</table>
	</td>
</tr>
</table>
</form>
<script language="javascript">
Calendar.enabled = true;

function init() {
	changeProject($('idProjectList'));
	<? if ($tid > 0) { ?>
	changeTask($('idTaskList'), <?=$task['task_log_task']?>);
	<? } ?>
}

setTimeout('init()', 250);
</script>
